<?php
    require_once '../config/config.php';
	require_once '../inc/db.php';
	require_once '../inc/get_country_from_ip.php';

	define("SUCCESS_CODE", 1);
	define("FAILURE_CODE", -1);

	if (isset($_POST['ip']) || isset($_GET['ip'])) {
		if (isset($_POST['ip'])) {
			$visitor = $_POST['ip'];
		}else{
			$visitor = $_GET['ip'];
		}
		$countryCode = ip_info($visitor, "Country Code");
		$city = ip_info($visitor, "City");

		if ($countryCode == '' || $city == '') {
			echo FAILURE_CODE;
			exit();
		}
		
		$query = "SELECT city from newsletter_certain_nearby WHERE country_code = ?";
		$stmt = $mysqli->prepare($query);
	    if ($stmt) {
	    	$stmt->bind_param("s",$countryCode);
	        if($stmt->execute()){
	            $stmt->bind_result($cityDb);
				$ok = false;
	            while($stmt->fetch()){
	            	$stmt->bind_result($cityDb);
	            	if(normalizeString($cityDb) == normalizeString($city)){
	            		$ok = true;
	            		break;
	            	}
	            }
	            if ($ok) {
	            	echo SUCCESS_CODE;
	            	exit();
	            }
	            $stmt->close();
	        }
	    }else{
	        die("Error:  ".$query);
	    }
		// Check nearby
		$query = "SELECT place FROM newsletter_nearest";
		$stmt = $mysqli->prepare($query);
		if($stmt){
			$stmt->execute();
			$stmt->bind_result($place);
			$ok = false;
			while ($stmt->fetch()) {
				if($city == $place) {
					$ok = true;
					break;
				}
			}
			if ($ok) {
				echo SUCCESS_CODE;
            	exit();
			}
		}else{
			die("Error: ".$query);
		}
			
		echo FAILURE_CODE;
    	exit();
	}//end if isset($_POST['ip']) || isset($_GET['ip'])
	function normalizeString($str)
	{
	    return str_replace(array("\n", "\t", " ", "-", "_"), NULL, strtolower(trim($str)));
	}
?>